<?php

namespace App\Http\Controllers\Api;

use App\Assessment;
use App\Config;
use App\Follow;
use App\Http\Requests\UserPersonnelUpdate;
use App\Invitationit;
use App\Position;
use App\PrivacSet;
use App\Socialite;
use App\TalentsSystemOrder;
use App\UserPersonnel;
use App\WhoLookMy;
use App\YiJing;
use EasyWeChat\Factory;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Auth;

class UserPersonnelController extends Controller
{
    /**
     * @param UserPersonnel $userPersonnel
     * @return \Illuminate\Contracts\Routing\ResponseFactory|\Symfony\Component\HttpFoundation\Response
     * 初始化 判断用户是否登陆过人才系统
     */
    public function index(UserPersonnel $userPersonnel)
    {
        $id = Auth::id();
        $info = $userPersonnel::where('user_id', $id)->first();
        if ($info) {
            return response(['message' => '欢迎', 'status' => 1, 'data' => $info]);
        }
        $userPersonnel->user_id = $id;
        $pre = $userPersonnel->save();
        if ($pre) {
            //初始化隐私设置
            if (!PrivacSet::where('uid', $id)->first()) {
                PrivacSet::create(['uid' => $id]);
            }
            return response(['message' => '欢迎', 'status' => 1, 'data' => $userPersonnel::where('user_id', $id)->first()]);
        }
        return response(['message' => '系统繁忙，请稍后重试', 'status' => 0], 400);
    }

    /**
     * @param UserPersonnelUpdate $request
     * @param UserPersonnel $userPersonnel
     * @return \Illuminate\Contracts\Routing\ResponseFactory|\Symfony\Component\HttpFoundation\Response
     * 修改 性别 座右铭  职业
     */
    public function upUserInfo(UserPersonnelUpdate $request, UserPersonnel $userPersonnel)
    {
        if ($userPersonnel::where('user_id', Auth::id())->update($request->only(['motto', 'sex', 'position', 'identity']))) {
            return response(['message' => '修改成功', 'data' => $userPersonnel::where('user_id', Auth::id())->first()]);
        }
        return response(['message' => '修改失败', 'data' => $userPersonnel::where('user_id', Auth::id())->first()], 400);
    }

    /**
     * @param Request $request
     * 查看他人信息   这里需要配合隐私设置
     */
    public function lookOthersInfo(Request $request)
    {
        $uid = $request->uid;//被查看者id
        $my = Auth::id();
        //查看他人个人信息还是公司信息
        $identity = $request->identity;
        //我的身份
        $type = UserPersonnel::where('user_id', $my)->value('identity');
        //他的隐私设置
        $privacy = PrivacSet::where('uid', $uid)->first();
        if ($identity == 1) {//查看个人信息
            $info = UserPersonnel::where('user_id', $uid)->with(['user', 'basic', 'work', 'education', 'intention', 'language', 'project', 'flaunt'])->first();
            if ($info) {
                $info->yijing = YiJing::orderBy('id', 'desc')->where('user_id', $uid)->first(); //获取最新易经评估
                $info->xinlixue = Assessment::orderBy('id', 'desc')->where('user_id', $uid)->with(['sort'])->first();//获取最新心理学评估
                //是否显示个人评估
                if ($request->has('is_pinggu')) {
                    if (!$request->is_pinggu) {
                        $info->yijing = null;
                        $info->xinlixue = null;
                    }
                } else {
                    if (!$privacy->is_assess_psychology) {//不现实心理学评估
                        $info->xinlixue = null;
                    }
                    if (!$privacy->is_assess_yijing) {
                        $info->yijing = null;
                    }
                }
                //是否已关注
                $is_follow = 0;
                if (Follow::where('active_id', $my)->where('by_id', $uid)->first()) {
                    $is_follow = 1;
                }
                //是否已邀请
                $is_invite = 0;
                if (Invitationit::where('user_id', $my)->where('by_id', $uid)->first()) {
                    $is_invite = 1;
                }
                $info->is_follow = $is_follow;
                $info->is_invite = $is_invite;
            }
            //个人图片转数组
            if ($info->flaunt) {
                if ($info->flaunt->image) {
                    $info->flaunt->image = explode(',', $info->flaunt->image);
                }
            }
        } else {//查看公司信息
            $info = UserPersonnel::where('user_id', $uid)->with(['companyInfo', 'position'])->first();
            //公司图片转数组
            if ($info->companyInfo) {
                if ($info->companyInfo->image) {
                    $info->companyInfo->image = explode(',', $info->companyInfo->image);
                }
            }
            if ($info) {
                //是否已关注
                $is_follow = 0;
                if (Follow::where('active_id', $my)->where('company_id', $uid)->first()) {
                    $is_follow = 1;
                }
                $info->is_follow = $is_follow;
            }
        }
        //记录到谁看过我
        if ($uid != $my) {
            if (WhoLookMy::where('user_id', $my)->where('mubiao_id', $uid)->first()) {
                WhoLookMy::where('user_id', $my)->where('mubiao_id', $uid)->update(['type' => $type]);
            } else {
                WhoLookMy::create(['user_id' => $my, 'mubiao_id' => $uid, 'type' => $type]);
            }
        }
        return response(['info' => $info, 'privacy' => $privacy]);
    }


    //人才推荐列表 默认推荐vip
    public function talentsRecommend(Request $request)
    {
        $pageSize = $request->page_size ? $request->page_size : 15;
        $search = $request->search;
        $order = $request->order;
        $list = UserPersonnel::where('id', '>', 0)
            ->where('identity', 1)
            ->with(['user', 'basic'])
            ->withCount(['workNumber']);
        if ($search) {
            $list = $list->where('position', 'like', '%' . $search . '%');
        }
        if ($order) {
            if ($order == 'updated_at') {//根据刷新简历时间排序
                $list = $list->orderBy('updated_at', 'desc')
                    ->orderBy('vip_over_time', 'desc')
                    ->orderBy('graded', 'desc');
            }
            if ($order == 'graded') {//根据信用评分排序
                $list = $list->orderBy('graded', 'desc')
                    ->orderBy('vip_over_time', 'desc')
                    ->orderBy('updated_at', 'desc');
            }
            if ($order == 'vip_over_time') {//根据是否是vip
                $list = $list->orderBy('vip_over_time', 'desc')
                    ->orderBy('updated_at', 'desc')
                    ->orderBy('graded', 'desc');
            }
        } else {
            $list = $list->orderBy('vip_over_time', 'desc')
                ->orderBy('updated_at', 'desc')
                ->orderBy('graded', 'desc');
        }
        $list = $list->paginate($pageSize);
        return $list;
    }

    /**
     * @param Request $request
     * @return mixed
     * 职位列表
     */
    public function zhiwei(Request $request)
    {
        $pageSize = $request->page_size ? $request->page_size : 15;
        $list = Position::where('uid', '>', 0);

        if ($request->position_name) {
            $list = $list->where('position_name', 'like', '%' . $request->position_name . '%');
        }
        //排序
        if ($request->order) {
            $list = $list->orderBy($request->order, 'desc');
        }
        return $list->with(['userPersonnel' => function ($query) {
            $query->where('identity', 2)->orderBy('vip_over_time', 'desc')
                ->orderBy('updated_at', 'desc');
        }, 'companyInfo'])->paginate($pageSize);
    }

    /**
     * @param Request $request
     * @return mixed
     * 公司列表
     */
    public function gongsi(Request $request)
    {
        $pageSize = $request->page_size ? $request->page_size : 15;

        $list = \App\CompanyInfo::where('uid', '>', 0);

        if ($request->cname) {
            $list = $list->where('cname', 'like', '%' . $request->cname . '%');
        }
        return $list->with(['userPersonnel' => function ($query) {
            $query->where('identity', 2)->orderBy('vip_over_time', 'desc')
                ->orderBy('updated_at', 'desc');
        }])->paginate($pageSize);
    }

    //生成订单
    public function createOrder($user_id, $price, $month, $goods_name = '')
    {
        $data = [];
        $data['user_id'] = $user_id;
        $data['order_number'] = time() . $user_id . rand(10000, 99999);
        $data['goods_name'] = $goods_name;
        $data['month'] = $month;
        $data['price'] = $price;//元
        $data['pay_type'] = 'WXPAY';
        $order = TalentsSystemOrder::create($data);
        return $order;
    }

    /**
     * @return mixed
     * 获取vip单价
     */
    public function getVipUnit()
    {
        return Config::where('key', 'vip_month_unit')->value('value');
    }

    /**
     * @param Request $request
     * @return array|\Illuminate\Contracts\Routing\ResponseFactory|string|\Symfony\Component\HttpFoundation\Response
     * @throws \EasyWeChat\Kernel\Exceptions\InvalidConfigException
     * 开通vip
     */
    public function openVip(Request $request)
    {
        $uid = Auth::id();
        $good_name = '开通VIP';
        $month = $request->month;
        $unit = Config::where('key', 'vip_month_unit')->value('value');
        $price = $unit * $month;//价格
        //生成订单
        $order = $this->createOrder($uid, $price, $month, $good_name);
        if (!$order) {
            return response(['message' => '下单失败'], 400);
        }

        $payment = Factory::payment(config('wechat.payment.default'));
        $openid = Socialite::where('user_id', Auth::id())->where('driver', 'wechat')->value('open_id');
        $notifyUrl = url('/api/vipNotify', ['wxpay' . '-' . $order->id]);
        if (!$openid) {
            return response(['尚未绑定微信'], 401);
        }
        $attribute = [
            'body' => '天南山文化',
            'detail' => '天南山文化',
            'out_trade_no' => $order->order_number,
            'total_fee' => $order->price * 100,
            'notify_url' => $notifyUrl,
            'trade_type' => 'JSAPI',
            'openid' => $openid,
        ];
        $result = $payment->order->unify($attribute);
        if ($result['return_code'] == 'SUCCESS' && $result['result_code'] == 'SUCCESS') {
            return $payment->jssdk->bridgeConfig($result['prepay_id']);
        }
        return response(['message' => '支付信息核对中,请稍后查看支付结果'], 400);
    }

    /**
     * @return false|string
     */
    public function getVipOverTime()
    {
        $time = UserPersonnel::where('user_id', Auth::id())->value('vip_over_time');
        $vip_over_time = date('Y-m-d H:i:s', $time);
        if ($vip_over_time < date('Y-m-d H:i:s')) {
            $vip_over_time = '您还不是VIP用户';
        }
        return $vip_over_time;
    }

}
